package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 22.6.7
     * 移动端 订单管理 下单
     *
     * @param orders
     * @return
     */
//    @PostMapping("/submit")
//    public R<String> submit(@RequestBody Orders orders) {
//        log.info("订单数据：{}", orders);
//        orderService.submit(orders);
//        return R.success("下单成功");

    @PostMapping("/submit")
//    @CacheEvict(value = "orderCache",allEntries = true)
    public R<String> submit (@RequestBody Orders orders){
        log.info("订单数据 {}",orders);
        Long submit = orderService.submit(orders);
        return R.success(submit.toString(),"下单成功");
    }

    /**
     * 22.6.7
     * 移动端 订单管理 订单信息查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
//    @Cacheable(value = "orderCache",key = "#page + '_' + #pageSize")
    public R<Page> page(int page, int pageSize) {
        //1. 构造分页构造器对象
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrderDto> pageDto = new Page<>(page, pageSize);
        //2. 构造orders表的查询构造器
        LambdaQueryWrapper<Orders> queryWrapper1 = new LambdaQueryWrapper<>();
        //2.1 添加查询条件
        queryWrapper1.eq(Orders::getUserId, BaseContext.getCurrentId());
        queryWrapper1.orderByDesc(Orders::getOrderTime);
        //3.1 执行查询
        orderService.page(pageInfo, queryWrapper1);
        //4. 获取分页信息
        List<Orders> records = pageInfo.getRecords();
        List<OrderDto> orderDtos = records.stream().map((item) -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(item, orderDto);
            Long orderId = item.getId();
            //构造order_detail表的查询构造器
            LambdaQueryWrapper<OrderDetail> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(OrderDetail::getOrderId, orderId);
            List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper2);
            orderDto.setOrderDetails(orderDetails);
            return orderDto;
        }).collect(Collectors.toList());
        BeanUtils.copyProperties(pageInfo, pageDto, "records");
        pageDto.setRecords(orderDtos);
        return R.success(pageDto);

    }

    @PostMapping("/again")
//    @CacheEvict(value = "orderCache",allEntries = true)
    public R<String> oneMoreOrder(@RequestBody Map map) {
        //获取从前端传入的订单号
        Object orderId = map.get("id");
        //获取当前用户信息
        long userId = BaseContext.getCurrentId();
        //构造查询构造器
        LambdaQueryWrapper<ShoppingCart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件 用户id
        cartLambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);
        //移除当前用户的购物车商品
        shoppingCartService.remove(cartLambdaQueryWrapper);
        //构造订单明细表查询器
        LambdaQueryWrapper<OrderDetail> detailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件 订单id
        detailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orderId);
       //根据条件列出订单明细表的所有数据存储在集合中
        List<OrderDetail> orderDetailList = orderDetailService.list(detailLambdaQueryWrapper);
        //先获取符合条件的订单明细表中的菜品或套餐存入购物车对象加入购物车集合
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if (dishId != null) {
                shoppingCart.setDishId(dishId);
            } else {
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());//菜品名或者套餐名
            shoppingCart.setDishFlavor(item.getDishFlavor());//菜品口味
            shoppingCart.setNumber(item.getNumber());//菜品或套餐数量
            shoppingCart.setAmount(item.getAmount());//购物车商品总金额
            shoppingCart.setCreateTime(LocalDateTime.now());//加购时间
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCartList);
        return R.success("操作成功");
    }


    /*=========================*/

    /**
     *查询订单明细
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R page(@RequestParam(name ="page" ,required =false,defaultValue = "1")Integer page,
                  @RequestParam(name ="pageSize" ,required =false,defaultValue = "10")Integer pageSize,
                  @RequestParam(name ="number" ,required =false)Long number,
                  @RequestParam(name ="beginTime" ,required =false)String  beginTime,
                  @RequestParam(name ="endTime" ,required =false)String  endTime ){
        Object all = orderService.findAll(page, pageSize, number, beginTime, endTime);

        return R.success(all);
    }

    /**
     * 修改订单状态
     * @param orders
     * @return
     */
    @PutMapping
    public R changeStatus(@RequestBody Orders orders) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getId, orders.getId());
        orderService.update(orders, wrapper);
        return R.success("已经派送!");
    }

}
